package com.letv.so.servlet;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.letv.so.bean.AlbumBean;
import com.letv.so.bean.VideoBean;
import com.letv.so.constants.Constants;
import com.letv.so.constants.PlayStreamsMapping;
import com.letv.so.util.BisUtil;
import com.letv.so.util.SoKeyUtil;
import com.letv.so.util.SpecialFieldUtil;
import com.letv.so.util.StringUtil;
import com.letv.so.util.ThreadLocalUtil;

/**
 * cbase详情接口
 *
 * @author wenjian
 *
 */
public class QueryCbaseServlet extends AbstractQueryDataServlet {

	private static final long serialVersionUID = -2626713538347997214L;
	private static Logger logger = Logger.getLogger(QueryCbaseServlet.class);

	/**
	 * 查询专辑详情
	 */
	@Override
    protected String query(Map<String, Object> rule) {
        String reData = "";
        if (rule.get("soKey") != null || rule.get("letvOriginalId") != null) {
            reData = oldQuery(rule);
        } else if (rule.get("lid") != null) {
            reData = queryStarByLid(rule.get("lid").toString(),(String) rule.get("sid"));
        }
		return reData;
	}

    private String queryStarByLid(String leid,String sid) {
        String starid = getStarId(leid);
        logger.info("leid="+leid+",starid="+starid);
        String reData = "";
        if (starid != null) {
            String sokey = SoKeyUtil.getSoKey(Constants.SRC_VRS, Constants.STAR, starid,true);
            reData = queryDataService.get(sid,sokey);// 获得cbase数据
            if (StringUtil.isBlank(reData)) {
                logger.warn("soKey:"+sokey+" get val from cbase为空!");
                return "{}";
            } else {
                JSONObject star = JSON.parseObject(reData);
                if (StringUtils.isNotBlank(ThreadLocalUtil.getFrom())) {
                    getJSONStr(star);
                }
                reData = star.toJSONString();
                logger.info("data="+reData);
            }
            if (TRADITIONAL.contains(ThreadLocalUtil.getLang())){
                reData = converter.convert(reData);
            }
            
        }
        return reData;
    }

    private void getJSONStr(JSONObject star) {
        Map<String,List<String>> config = rtnkeys.get("star");
        if (config !=null) {
            List<String> keys = config.get(ThreadLocalUtil.getFrom());
            if ( keys !=null){
                Iterator<Map.Entry<String, Object>> entrys = star.entrySet().iterator();
                while(entrys.hasNext()) {
                    String key = entrys.next().getKey();
                    if (keys.contains(key)) {
                        continue;
                    } else {
                        entrys.remove();
                        star.remove(key);
                    }
                }
            }else {
                star.remove("related_ids");
            }
        } 
    }

    private String getStarId(String sid) {
        return queryDataService.get(LE_ID_MAP_PERFIX+sid);
    }

    private String oldQuery(Map<String, Object> rule) {
        long starttime = System.currentTimeMillis();
        String time = "";
        String sid = (String) rule.get("sid");
        String pcp = (String) rule.get("pcp");
        String website_id_list = (String) rule.get("website_id_list");
        boolean ifTv = !StringUtils.isBlank(pcp) && Constants.PCP_FOR_CIBN.equals(pcp);
        String soKey = this.getSoKey(rule);
        if(StringUtils.isBlank(soKey)) {
            return "{}";
        }
        String reData = "";
        try {
            int dataType = SoKeyUtil.getDataType(soKey);// 通过sokey意义，判断数据类型
            int videoListSize = (Integer) rule.get("videoListSize");// 获得request剧集列表个数
            int pn = (Integer) rule.get("pn");//
            int ps = (Integer) rule.get("ps");// 每页多少个
            String soData = queryDataService.get(sid,"inc"+soKey);// 获得cbase数据
            if (StringUtils.isBlank(soData)) {
                soData = queryDataService.get(sid,soKey);// 获得cbase数据
            }

            if (StringUtil.isBlank(soData) && dataType != Constants.ALBUM) {
                return "{}";
            }
            //临时方案处理cmsimg数据,soKey=letv_cmsimg_0_0
            if (StringUtils.isNotBlank(soKey) && "newletv_cmsimg_0_0".equals(soKey)) {
                JSONArray jsonArray = JSONArray.parseArray(soData);
                int size = jsonArray.size();
                //pn默认为1，ps默认为50
                int fromIndex = pn * ps;
                int toIndex = (pn+1) * ps;
                List<Object> list = new ArrayList<Object>();
                if (toIndex<=size) {
                    list = jsonArray.subList(fromIndex, toIndex);
                }else {
                    if (fromIndex<size) {
                        list = jsonArray.subList(fromIndex, size);
                    }
                }
                logger.info(sid+" ,soKey:letv_cmsimg_0_0 get val from cbase:"+list.size());
                return JSON.toJSONString(list);
            }

            switch (dataType) {
            case Constants.ALBUM:
                AlbumBean album = CommonServlet.getDetailAlbum(queryDataService, soKey, sid, soData, ifTv, website_id_list);
                if (album == null) {
                    logger.warn(sid+ " ,soKey:"+soKey+" album==null ");
                    return "{}";
                }
                this.formatAlbum(album, ifTv);
                if (videoListSize > 0 && soKey.contains("newmms")) {// request要求有剧集列表，则封装
                    time = setVideoList(sid, soKey, album, videoListSize,pn,ps,true, ifTv);
                }
                if (TRADITIONAL.contains(ThreadLocalUtil.getLang())){
                    long  tt = System.currentTimeMillis();
                    album.sample2traditional(converter);
                    logger.info("QueryCbaseServlet,album sample to traditional total time|"+(System.currentTimeMillis()-tt));
                }
                reData = JSON.toJSONString(album, SerializerFeature.WriteTabAsSpecial);// 转为json格式
                break;
            case Constants.VIDEO:
                JSONObject videoInfo = JSON.parseObject(soData);
                super.setPayAndDownFlag(videoInfo);
                reData = videoInfo.toJSONString();
                break;
            default:
                reData = soData;
                break;
            }
            if (dataType != Constants.ALBUM && TRADITIONAL.contains(ThreadLocalUtil.getLang())){
                reData = converter.convert(reData);
            }
        } catch (Exception e) {
            logger.error(sid+" ,soKey:"+soKey+" error! return \"{}\"", e);
            return "{}";
        }
        logger.info(sid+",QueryCbaseServlet, total time=["+(System.currentTimeMillis()-starttime)+"],cbase time=["+time+"]");
        return reData;
    }

    /**
     * 将cbase中存储的专辑按需求格式化
     * @param albumBean AlbumBean
     * @param ifTv boolean, true--上tv, false--不上tv
     */
    private void formatAlbum(AlbumBean albumBean, boolean ifTv) {
        if(null == albumBean) {
            return;
        }
        try {
            if(null == albumBean.getIspay()) {
                albumBean.setIspay("0");
            }
            albumBean.setWebsite_album_id(albumBean.getVid());
            albumBean.setVid(null);
            this.addPosterPrefix(albumBean.getStarsPoster());
            this.addPosterPrefix(albumBean.getDirectoriesPoster());
            String source_list = "";
            JSONObject source_list_json = albumBean.getSource_list_json();
            if(null != source_list_json) {
                if(ifTv) {
                    source_list = null==source_list_json.getString(Constants.PUSHFLAG_TV) ? "" : source_list_json.getString(Constants.PUSHFLAG_TV);
                    albumBean.setSource_list(source_list);
                } else {
                    source_list = null==source_list_json.getString("default") ? "" : source_list_json.getString("default");
                    albumBean.setSource_list(source_list);
                }
            }
            String extData = albumBean.getExtData();
            if(StringUtils.isNotBlank(extData)) {
                JSONObject extDataJson = JSON.parseObject(extData);
                albumBean.setPay_type(extDataJson.getString("pay_type"));
                albumBean.setIs_coupon(extDataJson.getString("is_coupon"));
            }
        } catch(Exception e) {
            logger.error("format album error,album_id=" + albumBean.getAid(), e);
        }
    }

    /**
     * 添加海报前缀
     * @param posterMapList List<Map<String, Object>>
     */
    private void addPosterPrefix(List<Map<String, Object>> posterMapList) {
        if(null == posterMapList || posterMapList.size() == 0) {
            return;
        }
        for(Map<String, Object> posterMap : posterMapList) {
            Object poster = posterMap.get("poster");
            if(null == poster || StringUtils.isBlank(poster.toString())) {
                posterMap.put("posterPrefix", "");
                continue;
            }
            String posterStr = poster.toString();
            String[] posterArray = posterStr.split("/");
            if(null == posterArray || posterArray.length <= 1) {
                posterMap.put("posterPrefix", "");
                continue;
            }
            String removeStr = posterArray[posterArray.length - 1];
            posterMap.put("posterPrefix", posterStr.substring(0, posterStr.lastIndexOf(removeStr)));
        }
    }

    /**
     * 得到本次请求的sokey（主关键字）
     * @param requestParameter Map<String, Object>, request请求参数
     * @return String, 为空或出错则返回Null
     */
    private String getSoKey(Map<String, Object> requestParameter) {
        if(null == requestParameter) {
            return null;
        }
        String result = null;
        Object sid = requestParameter.get("sid");
        try {
            Object soKey = requestParameter.get("soKey");
            if(null != soKey) {
                String sokeyString = (String)soKey;
                if(!StringUtils.isBlank(sokeyString)) {
                    return sokeyString;
                }
            }
            Object letvOriginalId = requestParameter.get("letvOriginalId");
            if(null == letvOriginalId) {
                return null;
            }
            String letvOriginalIdString = letvOriginalId.toString();
            if(StringUtils.isBlank(letvOriginalIdString)) {
                return null;
            }
            String lesoId = null;
            if(letvOriginalIdString.indexOf(Constants.LESO_ALBUM_PERFIX) == 0) {
                lesoId = letvOriginalIdString.split("_")[1];
            } else if(letvOriginalIdString.indexOf(Constants.VRS_ALBUM_PERFIX) == 0) {
                String jsonString = queryDataService.get(sid.toString(), "mapping" + letvOriginalIdString);
                if(StringUtils.isBlank(jsonString)) {
                    return null;
                }
                JSONObject root = JSON.parseObject(jsonString);
                lesoId = root.getString("leso_album_id");
            }
            if(!StringUtils.isBlank(lesoId)) {
                result = new StringBuffer("").append("newmms_leso_a_").append(lesoId).toString();
            }
        } catch(Exception e) {
            logger.error("get sokey error,sid=" + sid, e);
            result = null;
        }
        return result;
    }

    /**
     * 超级抢先看重新设置操作
     * @param album
     */
    private void resetAlbumBeanForFastView(AlbumBean album){
    	String vids = album.getVids();
    	String idEpisodes = album.getVidEpisode();
    	String[] tmpVidArray ;
		String[] tmpIdEpisodes;
		if (StringUtil.isNotBlank(vids)){
			tmpVidArray =  vids.split(",");
			tmpIdEpisodes =  idEpisodes.split(",");
		}else{
			tmpVidArray = new String[]{};
			tmpIdEpisodes = new String[]{};
		}
		
		vids = "";
		idEpisodes = "";
		int count = 0;
		for (int i =0;i< tmpVidArray.length; i++){
				String soVideoKey = "newmms_vrs_v_"+tmpVidArray[i];
				String soIncVideoKey = "inc"+soVideoKey;
				
				String resultSoStr = queryDataService.get(soVideoKey);
				String resultIncSoStr = queryDataService.get(soIncVideoKey);
				if (StringUtil.isNotBlank(resultSoStr) || StringUtil.isNotBlank(resultIncSoStr) ){
					if (StringUtil.isEmpty(vids)){
						vids += tmpVidArray[i];
					}else{
						vids += ","+tmpVidArray[i];
					}
				}else{
					count++;
				}
		}
		
		for (int j= 0 ; j<tmpIdEpisodes.length; j++){
			if(StringUtil.isNotEmpty(tmpIdEpisodes[j])){
				int index = tmpIdEpisodes[j].indexOf("-");
				String key = tmpIdEpisodes[j].substring(index+1);
				
				if (StringUtil.isNotEmpty(vids))
					if (vids.contains(key) ){
						if (StringUtil.isEmpty(idEpisodes)){
							idEpisodes += tmpIdEpisodes[j];
						}else{
							idEpisodes += ","+tmpIdEpisodes[j];
						}
					}
			}
			
		}
		album.setVids(vids);
		try {
		    album.setNowEpisodes(""+(Integer.parseInt(album.getNowEpisodes())-count+1));
		} catch(Exception e) {
		}
        album.setVidEpisode(idEpisodes);
        //设置是否更新完毕
        if (StringUtil.isNotEmpty(album.getEpisodes())){
        	if (!album.getEpisodes().equals(album.getNowEpisodes())){
        		album.setIsEnd("0");
        	}
        }
		
    }

	/**
	 * 封装剧集列表
	 *
	 * @param album
	 * @param videoListSize
	 * @param ifTv 
	 */
	private String setVideoList(String sid, String soKey1, AlbumBean album, int videoListSize,int pn, int ps,boolean mmsFlag, boolean ifTv) {
		String time = "";
		long st1 = System.currentTimeMillis();
		String url = album.getUrl();
		String subSrc = album.getSubSrc();
		if (!StringUtil.isBlank(url) && (!StringUtil.isBlank(subSrc)) && ("nets".equals(subSrc) || "pan".endsWith(subSrc))) {
			int len = url.lastIndexOf('/') + 1;
			album.setPanid(url.substring(len));
			album.setSubSrc("nets");
        } else {
        	album.setPanid("");
        }
		String category = album.getCategory();
		List<VideoBean> videoList = new ArrayList<VideoBean>();
		List<String>  tags = new ArrayList<String>();
		List<String> videoTypes = new ArrayList<String>();
		String tagList = "";
		String orderList = "";
		try {
			if (Constants.SRC_VRS.equals(album.getSrc())) {// vrs专辑的剧集列表需要根据album.VidEpisode和.vids二次取cbase
				String aid = album.getAid();
				String idEpisodes = album.getVidEpisode();
				String vids = album.getVids();
				String ralbums = album.getSeriesAlbumIds();
				long s1 = System.currentTimeMillis();
				if(!StringUtils.isBlank(ralbums)){
					setRAlbum(ralbums,album);
				}
				String pushFlag = album.getPushFlag();
				if (StringUtils.isNotEmpty(pushFlag)){
					if (pushFlag.contains(Constants.FAST_VIEW)){//如果是抢先看的专辑
						resetAlbumBeanForFastView(album);
						vids = album.getVids();
						idEpisodes = album.getVidEpisode();
					}
				}
					
				album.setLetv_original_id(Constants.VRS_ALBUM_PERFIX+aid);
				logger.debug(sid+","+soKey1+",SRC_VRS setRAlbum cost time="+(System.currentTimeMillis()-s1));
				List<String> vidLists = new ArrayList<String>();
				List<String> orders = new ArrayList<String>();
				if (!StringUtil.isBlank(vids)) {
					String[] vidArray = vids.split(",");
					String[] idEpisodeArray = null;
					if (StringUtils.isNotBlank(idEpisodes)) {
						idEpisodeArray = idEpisodes.split(",");
                    } else {
                    	idEpisodeArray = new String[]{};
                    }
					// 电影电视剧动漫除外的频道视频列表倒序
					if (String.valueOf(Constants.MMS_MOVIE).equals(category) || String.valueOf(Constants.MMS_TV).equals(category) || String.valueOf(Constants.MMS_CARTOON).equals(category) || String.valueOf(Constants.MMS_OTHER).equals(category)) {
						vidArray = reverse1(vidArray);
					}else {
						idEpisodeArray = reverse1(idEpisodeArray);
					}
					long st2 = System.currentTimeMillis();
					logger.debug(sid+","+soKey1+",SRC_VRS setVideoList, cost time1=" + (st2-st1));
					List<String> allVidLists = Arrays.asList(vidArray);
					List<String> vidEpisodesLists = Arrays.asList(idEpisodeArray);
					logger.debug(sid+","+soKey1+" SRC_VRS vidEpisodesLists="+vidEpisodesLists+",size="+vidEpisodesLists.size());

					for (String vidEpisode : vidEpisodesLists) {//先添加正片vid
	                    int len = vidEpisode.indexOf("-");
	                    String vid = vidEpisode.substring(len+1);
	                    vidLists.add(vid);
	                    orders.add(vidEpisode.substring(0, len));//只有正片有order
                    }

					for (String vid : allVidLists) {//添加其他片vid
	                    if (!vidLists.contains(vid)) {
	                        vidLists.add(vid);
                        }
                    }

					int size = vidLists.size();
					logger.debug(sid+","+soKey1+" SRC_VRS retVids vidLists="+vidLists+",size="+size);
					//pn默认为1，ps默认为50
					ps = videoListSize > ps?ps:videoListSize;
					int fromIndex = pn * ps;
					int toIndex = (pn+1) * ps;
					List<String> retVids = new ArrayList<String>();
					if (toIndex<=size) {
						retVids = vidLists.subList(fromIndex, toIndex);
                    }else {
						if (fromIndex<size) {
							retVids = vidLists.subList(fromIndex, size);
                        }
					}
					logger.debug(sid+","+soKey1+",SRC_VRS retVids fromIndex="+fromIndex+",toIndex="+toIndex+",retVids.size="+retVids.size());
					List<String> soDataList = new ArrayList<String>();
					long st3 = System.currentTimeMillis();
					logger.debug(sid+","+soKey1+",SRC_VRS retVids, cost time2=" + (st3-st2));
					multiGetDataByIds(sid, soDataList, retVids, album.getSrc(), mmsFlag);
					long st34 = System.currentTimeMillis();
					time = (st34-st3)+",videolist="+retVids.size();
					logger.info(sid+" ,"+soKey1+",SRC_VRS retVids,from cbase total time=[" + (st34-st3)+"],videolist="+retVids.size());
					int i = 1;
					for (String soData : soDataList) {
						if (!StringUtil.isBlank(soData)) {
							VideoBean video = JSON.parseObject(soData, VideoBean.class);
							if(null == video) continue;
							String videoPushFlag = StringUtils.isBlank(video.getPushFlag()) ? "" : video.getPushFlag();
							String videoIsCibnCheck = StringUtils.isBlank(video.getGuoguang()) ? "" : video.getGuoguang();
							if(ifTv && (!videoPushFlag.contains(Constants.PUSHFLAG_TV) || "0".equals(videoIsCibnCheck))) continue;
							video.setPlayStreamsValue(this.getVideoPlayStreamsValue(video.getPlayStreams()));
							String videoType = video.getVideoType();
							if ((String.valueOf(Constants.TV).equals(category) || String.valueOf(Constants.CARTOON).equals(category))
									&& Constants.TYPE_ZHENGPIAN.equals(videoType)) {
								video.setUrl("http://www.letv.com/ptv/pplay/" + video.getAid() + "/" + i + ".html");
							} else {
								video.setUrl("http://www.letv.com/ptv/vplay/" + video.getVid() + ".html");
							}
							String videoUrl = video.getUrl();
							if (!StringUtil.isBlank(videoUrl)  && (!StringUtil.isBlank(subSrc)) && ("nets".equals(subSrc) || "pan".endsWith(subSrc))) {
								int len = videoUrl.lastIndexOf('/') + 1;
								video.setVideoPanid(videoUrl.substring(len));
					        } else {
					        	video.setVideoPanid("");
					        }
							if (StringUtils.isNotBlank(video.getPorder())) {
								videoTypes.add(video.getVideoType());
	                        }else {
	                        	videoTypes.add("null");
							}
							if (StringUtils.isNotBlank(video.getPorder())) {
								tags.add(video.getPorder());
	                        }else {
	                        	tags.add("null");
							}
							//每个视频添加唯一全局id
						    String porder = "1";
						    if (StringUtils.isNotBlank(video.getPorder())) {
						        porder = video.getPorder();
						    }
						    video.setGlobal_vid(aid+"_"+porder+"_"+BisUtil.MD5(video.getUrl()));
						    if (video != null) {
		                        if (TRADITIONAL.contains(ThreadLocalUtil.getLang())){
		                            video.sample2traditional(converter);
		                        }
		                        setPayAndDownFlag(video);
							    videoList.add(video);
						    }

						} else {
							tags.add("null");
						}
						i++;
					}
				}
				long st3 = System.currentTimeMillis();
				tagList = BisUtil.getTaglist(vidLists, ps,orders);
				orderList = BisUtil.getOrderlist(orders);
				logger.debug(sid+" ,"+soKey1+",SRC_VRS tagList&orderList cost time4=" + (System.currentTimeMillis()-st3));
            } else if (Constants.SRC_LESO.equals(album.getSrc()) || Constants.SRC_CP.equals(album.getSrc())) {// leso专辑的剧集列表根据album.videoPlayUrls解析生成
				String videoPlayUrls = album.getVideoPlayUrls();
                String[] vidArray = album.getOrderlist().split(",");
                String[] durationsArray = album.getVideo_durations() == null ? new String[0]
                        : album.getVideo_durations().split(",");
                String[] typeArray = album.getVideo_types() == null ? new String[0] : album.getVideo_types().split(",");
				 //死链map
				long st2 = System.currentTimeMillis();
                if (!SpecialFieldUtil.checkSingleField(this.rtnkeys, ThreadLocalUtil.getFrom(), "leso", "play_status",
                        true)) {
                    album.setPlay_status(null);
                }
				logger.debug(sid+" ,"+soKey1+",SRC_LESO deadlinkMap, cost time5=" + (st2-st1));
				if (!StringUtil.isBlank(videoPlayUrls)) {
					List<String> orders = new ArrayList<String>();
					String[] videoArray = videoPlayUrls.split(";");
					for (String vid : videoArray) {
						String[] videoFileds = vid.split("\\|");
						if (videoFileds.length==1) {//过滤不规范的数据
                            continue;
                        }
						orders.add(videoFileds[0]);
                    }
					List<String> vidLists = Arrays.asList(videoArray);
					//pn默认为0，ps默认为50
					ps = videoListSize > ps?ps:videoListSize;
					int size = vidLists.size();
					int fromIndex = pn * ps;
					int toIndex = (pn+1) * ps;
					List<String> retVids = new ArrayList<String>();
					List<String> retInfos = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getIntro()));
					List<String> subNames = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getVideoSubNames()));
					List<String> externalIds = BisUtil.subList(fromIndex, toIndex, BisUtil.getList(album.getExternalIds()));
					List<String> external_play_ids = BisUtil.subList(fromIndex, toIndex, BisUtil.getList(album.getExternal_play_ids()));
					// 只有SARSS端需要外网流截图
					List<String> images = new ArrayList<String>();
					if("letv".equals(subSrc)) {
					    images = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getVideoImages()));
					} else {
					    if(SpecialFieldUtil.checkSingleField(this.rtnkeys,ThreadLocalUtil.getFrom(), "leso", "videoList.images", true)) {
					        images = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getVideoImages()));
					    }
					}
	                List<String> deadinfo = new ArrayList<String>();
	                List<String> uidInfo = new ArrayList<String>();
	                List<String> letvOrininalSvidsInfo = new ArrayList<String>();
                    List<String> payPlatforms = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getPayPlatform()));
                    List<String> downloadPlatforms = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getDownloadPlatform()));
                    List<String> mids = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getMids()));
                    List<String> ispays = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getIsPays()));
					if (fromIndex >= size) {
					    return time;
					} else if ( fromIndex<size && toIndex > size ) {
						    toIndex = size;
					}
		            ArrayList<String> deadlinkList = new ArrayList<String>();
		            String deadlinks = album.getDeadlinks();
		            BisUtil.convertStr2List(deadlinks,deadlinkList);
	                ArrayList<String> globalVids = new ArrayList<String>();
	                BisUtil.convertStr2List(album.getUnIds(),globalVids);
	                ArrayList<String> letvOrininalSvids = new ArrayList<String>();
	                BisUtil.convertStr2List(album.getLetvOrininalSvids(),letvOrininalSvids);
					retVids = vidLists.subList(fromIndex, toIndex);
					deadinfo = deadlinkList.subList(fromIndex, toIndex);
					uidInfo = globalVids.subList(fromIndex, toIndex);
					letvOrininalSvidsInfo = letvOrininalSvids.subList(fromIndex, toIndex);
					logger.info(sid+" ,"+soKey1+" SRC_LESO retVids fromIndex="+fromIndex+",toIndex="+toIndex+",videolist="+retVids.size());
					String aid = album.getAid();
					long st22 = System.currentTimeMillis();
					logger.debug(sid+" ,"+soKey1+",SRC_LESO videolist, cost time6=" + (st22-st2));
					for (int i=0;i<retVids.size();i++) {
						String vid = retVids.get(i);
						if (StringUtil.isNotBlank(vid)) {
							String[] videoFileds = vid.split("\\|");
							if (videoFileds.length==1) {//过滤不规范的数据
	                            continue;
                            }
							String[] videoInfo = retInfos.size() > i ? retInfos.get(i).split("\\|") : new String[0];
							String[] subName = subNames.size() > i ? subNames.get(i).split("\\|") : new String[0];
							String[] image = images.size() > i ? images.get(i).split("\\|") : new String[0];
                            String[] ispayv = ispays.size() > i ? ispays.get(i).split("\\|") : new String[0];
                            String[] payPlatform = payPlatforms.size() > i ? payPlatforms.get(i).split("\\|") : new String[0];
                            String[] downPlatform = downloadPlatforms.size() > i ? downloadPlatforms.get(i).split("\\|") : new String[0];
                            String[] mid = mids.size() > i ? mids.get(i).split("\\|") : new String[0];
                            String[] externelid = externalIds.size() > i ? externalIds.get(i).split("\\|") : new String[0];
                            String[] external_play_id = external_play_ids.size() > i ? external_play_ids.get(i).split("\\|") : new String[0];
							VideoBean video = new VideoBean();
							video.setDataType(Constants.VIDEO);
							video.setAorder(videoFileds[0]);
							video.setUrl(videoFileds[1]);
							video.setName(videoInfo.length > 1 ? videoInfo[1] : "");
							video.setSubName(subName.length > 1 ? subName[1] : video.getName());
							video.setExternal_id(externelid.length > 1 ? externelid[1] : "");
			                String externalPlayIdJsonString = external_play_id.length > 1 ? external_play_id[1] : "";
			                if(StringUtils.isBlank(externalPlayIdJsonString)) {
			                    video.setExternal_play_id(new JSONObject());
			                } else {
			                    try {
			                        video.setExternal_play_id(JSON.parseObject(externalPlayIdJsonString));
			                    } catch(Exception externalPlayIdError) {
			                        video.setExternal_play_id(new JSONObject());
			                    }
			                }
							video.setIsPay(ispayv.length > 1 ? ispayv[1] : "0");
							video.setPayPlatform(payPlatform.length > 1 ? payPlatform[1] : null);
							video.setDownloadPlatform(downPlatform.length > 1 ? downPlatform[1] : null);
                            video.setVid(vidArray.length > i ? vidArray[i] : null);
                            video.setDuration(durationsArray.length > i ? durationsArray[i] : null);
                            video.setVideoType(typeArray.length > i ? typeArray[i] : null);
							video.setMid(mid.length > 1?mid[1]:null);
							if (image.length > 1) {
							    try {
							        video.setImages(image[1]);
							    }catch(Exception e){
							        logger.error("parse images for single video,error album id="+album.getAid(),e);
							    }
							} 
							tags.add(videoFileds[0]);
							String videoUrl = video.getUrl();
							if (!StringUtil.isBlank(videoUrl)  && (!StringUtil.isBlank(subSrc)) && ("nets".equals(subSrc) || "pan".endsWith(subSrc))) {
								int len = videoUrl.lastIndexOf('/') + 1;
								video.setVideoPanid(videoUrl.substring(len));
					        } else {
					        	video.setVideoPanid("");
					        }
							//添加死链
							if (deadinfo.size() > i) {
								video.setDeadlink(deadinfo.get(i));
                            } else {
                            	logger.debug(sid+" ,"+soKey1+",SRC_LESO videoPlayUrls 与 deadlinks 不匹配 ");
                            	video.setDeadlink("0");
                            }
							//每个视频添加唯一全局id
							String porder = "1";
		                	if (StringUtils.isNotBlank(video.getAorder())) {
		                		porder = video.getAorder();
	                        }
		                	video.setGlobal_vid(aid+"_"+porder+"_"+BisUtil.MD5(video.getUrl()));
	                        if (uidInfo.size() > i) {
	                             video.setUnid(uidInfo.get(i));
	                        } else {
	                             logger.debug(sid+" ,"+soKey1+",SRC_LESO videoPlayUrls 与 uuids 不匹配 ");
	                             video.setUnid("");
	                        }
	                        if (letvOrininalSvidsInfo.size() > i) {
	                            video.setLetvOrininalSvid(letvOrininalSvidsInfo.get(i));
	                        } else {
	                            video.setLetvOrininalSvid("");
	                        }
	                        if (TRADITIONAL.contains(ThreadLocalUtil.getLang())){
	                            video.sample2traditional(converter);
	                        }
	                        setPayAndDownFlag(video);
		                	videoList.add(video);
						} else {
							tags.add("null");
						}
                    }
					album.setSomePropertyNull();
					//album.setUnIds(null);
					logger.debug(sid+","+soKey1+",SRC_LESO videolist, cost time7=" + (System.currentTimeMillis()-st22));

					long st3 = System.currentTimeMillis();
					tagList = BisUtil.getTaglist(vidLists, ps,orders);
					orderList = BisUtil.getOrderlist(orders);
					logger.debug(sid+" ,"+soKey1+",SRC_LESO tagList, cost time8=" + (System.currentTimeMillis()-st3));
				}
			}
			if (videoList.size() > 0) {
			    int rmN = removeOneVideo(album.getAid(),videoList);
				album.setVideoList(videoList);
				album.setTaglist(tagList);
				album.setOrderlist(orderList);
				changeOrderLstAndEps(rmN,album);
			}
		} catch (Exception e) {
			logger.error(sid+",exception: ",e);
		}
		return time;
	}

	/**
	 * 获得媒资单视频码流id对应的码流值
	 * @param videoPlayStreams String, 码流id由,拼接而得的字符串，形如：
	 * "252132,252053,252018,252020"
	 * @return 码流id对应值，以,拼接，为空或出错则返回空字符串。形如：
	 * "value1,value2,value3,value4"
	 */
	private String getVideoPlayStreamsValue(String videoPlayStreams) {
	    if(StringUtils.isBlank(videoPlayStreams)) {
	        return "";
	    }
	    String result = "";
	    try {
	        StringBuffer resultBuffer = new StringBuffer("");
	        String separator = ",";
	        String[] videoPlayStreamsIdArray = videoPlayStreams.split(separator);
	        if(null == videoPlayStreamsIdArray || videoPlayStreamsIdArray.length == 0) {
	            return "";
	        }
	        for(int i = 0; i < videoPlayStreamsIdArray.length; i++) {
	            String id = videoPlayStreamsIdArray[i];
	            if(StringUtils.isBlank(id)) {
	                continue;
	            }
	            String value = PlayStreamsMapping.PLAYSTREAMS_PROPERTIES.getProperty(id);
                if(!StringUtils.isBlank(value)) {
                    resultBuffer.append(value).append(separator);
                }
	        }
	        result = resultBuffer.toString();
	        if(result.length() > 0 && result.endsWith(separator)) {
	            result = result.substring(0, result.length() - 1);
	        }
	    } catch(Exception e) {
	        result = "";
	    }
        return result;
    }

    private void changeOrderLstAndEps(Integer rmN, AlbumBean album) {
        if (rmN > 0 ) {
            String np =  album.getNowEpisodes();
            if (rmN.toString().equals(np)) {
                album.setNowEpisodes(""+(rmN-1));
            }
            String orderlst = album.getOrderlist();
            String removeStr = getRemoveStr(rmN);
            if (StringUtils.isNotEmpty(orderlst) && orderlst.contains(removeStr)) {
                album.setOrderlist(orderlst.replace(removeStr, ";"));
            }
         }
    }

/*    private void multiGetDataByIds(String sid, List<String> soDataList, List<String> retVids, String albumSrc, boolean mmsFlag) {
        String[] incsokeys = new String[retVids.size()];
        String[] sokeys = retVids.toArray(new String[retVids.size()]);
        String soKey =null;
        for (int i = 0;i< retVids.size();i++) {
            soKey = SoKeyUtil.getSoKey(albumSrc, Constants.VIDEO, retVids.get(i),mmsFlag);
            incsokeys[i] ="inc"+ soKey;
            sokeys[i] = soKey;
        }
        Map<String,Object> incData = queryDataService.getMulti(incsokeys);
        Map<String,Object> mdata = queryDataService.getMulti(sokeys);

        for (String key :incsokeys) {
            if (incData.get(key)!=null && !StringUtils.isBlank(incData.get(key).toString())) {
                soDataList.add(incData.get(key).toString());
            } else {
                String tmpkey = key.substring(3);
                if (mdata.get(tmpkey) !=null && !StringUtils.isBlank(mdata.get(tmpkey).toString())) {
                    soDataList.add(mdata.get(tmpkey).toString());
                } else {
                    logger.error(sid+" ,query cbase soKey=" + tmpkey + ", result is null");
                }
            }
        }

    }*/
	private void multiGetDataByIds(String sid, List<String> soDataList, List<String> retVids, String albumSrc, boolean mmsFlag) {
		String soKey =null;
		Integer size = retVids.size();
		int ps = 20;
		int pn = size/ps;
		for (int k=0;k<=pn;k++) {
		    int starIndex = ps * k;
		    int arrSize = starIndex + ps < size ? ps  : (size - starIndex);
		    String[] incsokeys = new String[arrSize];
		    String[] sokeys = new String[arrSize];
		    for (int i = 0;i<arrSize ;i++) {
		        int number = starIndex + i;
	            soKey = SoKeyUtil.getSoKey(albumSrc, Constants.VIDEO, retVids.get(number),mmsFlag);
	            incsokeys[i] ="inc"+ soKey;
	            sokeys[i] = soKey;
	        }
	        Map<String,Object> incData = queryDataService.getMulti(incsokeys);
	        Map<String,Object> mdata = queryDataService.getMulti(sokeys);

	        for (String key :incsokeys) {
	            if (incData.get(key)!=null && !StringUtils.isBlank(incData.get(key).toString())) {
	                soDataList.add(incData.get(key).toString());
	            } else {
	                String tmpkey = key.substring(3);
	                if (mdata.get(tmpkey) !=null && !StringUtils.isBlank(mdata.get(tmpkey).toString())) {
	                    soDataList.add(mdata.get(tmpkey).toString());
	                } else {
	                    logger.error(sid+" ,query cbase soKey=" + tmpkey + ", result is null");
	                }
	            }
	        }

		}
		
	}

	private void setRAlbum(String ids,AlbumBean album){

		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

			String[] albums = ids.split(",");
			for(String a:albums){
				if(!StringUtils.isBlank(a)){
					String albumStr = queryDataService.get("mms_vrs_a_"+a);// 获得cbase数据
					logger.debug("albumStr="+albumStr);
					AlbumBean abean =null;
					Map<String,Object> map = new HashMap<String,Object>();
					try {
						abean = JSON.parseObject(albumStr, AlbumBean.class);
					} catch (Exception e) {
						logger.error("parse album error", e);
					}
					if(null !=abean){
						map.put("aid", abean.getAid());
						map.put("name", abean.getName());
						map.put("images", abean.getImages());
					}
					list.add(map);
				}

			}

		album.setRelationAlbums(list);
	}

	private static String[] reverse1(String[] array) {
		String[] array1 = new String[array.length];
		int j=0;
		if(array.length>0){
			for (int i = array.length-1; i >=0 ; i--) {
				array1[j++]=array[i];
			}
			return array1;
		}
		return array;
	}

}
